package ru.arriah.servicedesk.web.admin.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class ManageSubordunatesAction extends DumbAction {
   protected EmployeeManagerLocalHome employeeManagerHome;

   public ManageSubordunatesAction() throws NamingException {
      super();

      employeeManagerHome =
         Utils.getEmployeeManagerHomeInterface();
   }

   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {       
       EmployeeManagerLocalObject employeeManager = 
         employeeManagerHome.create();       
              
       int employeeId = idVal(request.getParameter("employee_id"));
       int ownerId = idVal(request.getParameter("owner_id"));
       if (employeeId == 0) {
         
          addErrorMessage(
             request,
             config.getProperty("ERROR.EMPLOYEE_REQUIRED")
         );         
          
       } else {
       
       String action = request.getParameter("action");                             
       
       if (action.equals("add")) {
         employeeManager.addSubordinate(ownerId, employeeId);
         
         addInfMessage(
            request,
            config.getProperty("INF.SUBORDINATE.ADDED")
         );   
         
       } else if (action.equals("delete")) {
         employeeManager.deleteSubordinate(ownerId, employeeId);
         
         addInfMessage(
            request,
            config.getProperty("INF.SUBORDINATE.DELETED")
         );   
       }
       }
              
//Prepare employee List
                     
       Collection<EmployeeBean> subordinatesList = 
         employeeManager.selectSubordinates(ownerId);
       
       Collection<EmployeeBean> notSubordinatesList = 
         employeeManager.selectNotSubordinates(ownerId);
       
       employeeManager.remove();       

       request.setAttribute("employessList", subordinatesList);
       request.setAttribute("subordinatesList", notSubordinatesList);
       request.setAttribute("owner", ownerId);

       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}